#!/usr/bin/python
# -*- coding: utf-8 -*-
# 曹志强
# 展示界面
# 2023.12.19
from django.db.models import Count
# ...
# ...
from django_echarts.starter.sites import DJESite
from django_echarts.entities import Copyright, bootstrap_table_class

from pyecharts import options as opts
from pyecharts.charts import Bar, Timeline
from pyecharts.components import Table

from study.models import ActivityLearning

site_obj = DJESite(site_title='学习统计')

site_obj.add_widgets(copyright_=Copyright(start_year=2023, powered_by='振振公子'))

chart_description = '2023年1-12月，各类型学习次数统计。'

def get_list(year=2023):
    # list_querySet = (ActivityLearning.objects.filter(date__year=2023).exclude(theme=None).
    #         values('theme',"theme__name").annotate(count=Count('theme'))).filter(count__gt=10).order_by('-count')
    list_querySet = (ActivityLearning.objects.filter(date__year=year).exclude(theme=None).
            values('theme',"theme__name").annotate(count=Count('theme'))).order_by('-count')
    # 使用values_list方法选择要提取的字段，并转换为列表
    list_name = list(list_querySet.values_list('theme__name', flat=True))
    list_count = list(list_querySet.values_list('count', flat=True))
    return list_name,list_count

# http://127.0.0.1:8000/chart/fujian_forest_coverage/
@site_obj.register_chart(title='振振公子2023年学习次数统计', description = chart_description, catalog='基本信息',top=1)
def fujian_forest_coverage():
    import re
    list_name, list_count = get_list()
    for i in range(len(list_name)):
        # 你的字符串
        original_string = list_name[i]
        # 使用正则表达式在每两个字符之间插入换行符
        inserted_string = re.sub(r'(...)', r'\1\n', original_string)
        list_name[i] = inserted_string
    print(list_name,len(list_name))
    print(list_count,len(list_count))

    bar = Bar().add_xaxis(
        list_name
    ).add_yaxis(
        '学习次数', list_count
    ).set_global_opts(
        visualmap_opts=opts.VisualMapOpts(is_show=True, max_=100, min_=0)).set_series_opts(
        markline_opts=opts.MarkLineOpts(
            data=[
                opts.MarkLineItem(y=66.8, name=""),
            ]
        )
    )
    return bar

# @site_obj.register_chart(title='学习统计', catalog='基本信息', description='', top=4,
#                          nav_after_separator=True)
# def fj_data_table():
#     list_name, list_count = get_list()
#     list_table=[]
#     for i in range(len(list_name)):
#         list_table.append([list_name[i],list_count[i]])
#     # 使用列表推导式将整数列表转换为字符串列表
#     str_list = [[str(num) for num in list_count]]
#     table = Table()
#     table.add(["类型","次数"], list_table, attributes={'class': bootstrap_table_class(border=True, striped=True)})
#     return table

@site_obj.register_chart(title='历年学习统计', catalog='基本信息', description='2022-2023年历年学习统计', top=4,
                         nav_after_separator=True)
def fj_data_table_all():
    typename_last = None
    list_querySet = (ActivityLearning.objects.exclude(theme=None).
                     values("theme__name",'date__year').annotate(count=Count('id'))).order_by('-theme__name','-date__year')
    # 使用values_list方法选择要提取的字段，并转换为列表
    list_year = list(list_querySet.values_list('date__year', flat=True))
    list_name = list(list_querySet.values_list('theme__name', flat=True))
    list_count = list(list_querySet.values_list('count', flat=True))

    list_table=[]
    for i in range(len(list_name)):
        typename = list_name[i]
        if typename == typename_last:
            continue
        list_count=[]
        list_count.append(typename)
        for year in [2023,2022,2021,2020]:
            list_result = list_querySet.filter(date__year=year,theme__name=typename)
            if list_result.count()==0:
                count_year = 0
            else:
                count_year = list_result.first()['count']
            list_count.append(count_year)
        typename_last = typename
        list_table.append(list_count)
        # list_table.append([list_year[i],list_name[i],list_count[i]])
    # 按照2023年排序
    list_table = sorted(list_table, key=lambda x: x[1], reverse=True)
    # 使用列表推导式将整数列表转换为字符串列表
    table = Table()
    table.add(["类型","2023年","2022年","2021年","2020年"], list_table, attributes={'class': bootstrap_table_class(border=True, striped=True)})
    return table

    list_table=[]
    for i in range(len(list_name)):
        list_table.append([list_year[i],list_name[i],list_count[i]])
    # 使用列表推导式将整数列表转换为字符串列表
    table = Table()
    table.add(["年","类型","次数"], list_table, attributes={'class': bootstrap_table_class(border=True, striped=True)})
    return table

